//
//  MyExamViewController.m
//  Exam
//
//  Created by huangzhen on 2017/5/11.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "MyExamViewController.h"

#import "HChooseBankViewController.h"
#import "DIHTest.h"
#import "HAnswerTableViewCell.h"
#import "HExamHeadView.h"
#import "HtestCollectionViewCell.h"
#import "SizeToFit.h"
#import <TMCache.h>

#import "SingleSelectView.h"
#import "MultiSelectView.h"
#import "UIButton+BackgroundColor.h"

#import "Header.h"
#import "HCommon.h"

#import "HShowALLQuesView.h"
@interface MyExamViewController ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>

@property (strong, nonatomic) UICollectionViewFlowLayout *collectionViewLayout;

@property (strong, nonatomic) UICollectionView           *collectionView;

//数据源
@property (strong, nonatomic) NSMutableArray             *dataSource;
//答案
@property (strong, nonatomic) NSMutableArray             *resultArray;

@property (strong, nonatomic) NSMutableArray             *indexPathArray;
//当前选中的item
@property (assign, nonatomic) NSInteger                   currentSelectIndex;

@property (nonatomic, strong) NSMutableArray *array;

@property (nonatomic, strong) UIButton *button;

@end

@implementation MyExamViewController

- (instancetype)init {
    if (self) {
        self.array = [NSMutableArray new];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    self.button =[UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame=CGRectMake(20, 20, 100, 30);
    [self.button setTitle:@"切换题库" forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(showAllQuestions:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = self.button;

    
    self.button.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.button.titleLabel.font = [UIFont systemFontOfSize:16];
    self.button.layer.borderWidth = 1.0f;
    
    
    NSString *bankid= [[TMCache sharedCache]objectForKey:@"bankid"];
    NSString *bankName = [[TMCache sharedCache]objectForKey:@"bankName"];
    if (bankid.length > 0) {
        DIHTest *test = [[DIHTest alloc]init];
        [self.dataSource removeAllObjects];
        self.dataSource = [test getQuesWithBankID:bankid];
        [self.button setTitle:bankName forState:UIControlStateNormal];
        [self.collectionView reloadData];
        
    }

    
    UIBarButtonItem *execbtn = [[UIBarButtonItem alloc] initWithTitle:@"清空记录" style:UIBarButtonItemStylePlain target:self action:@selector(didDeleteButttonClicked:)];
    self.navigationItem.rightBarButtonItem = execbtn;

    
    [self initView];
    
}


- (void)showAllQuestions:(UIButton *)sender
{
    HChooseBankViewController *HQCDVC = [[HChooseBankViewController alloc]init];
    UINavigationController *navHQCDVC = [[UINavigationController alloc]initWithRootViewController:HQCDVC];
    DIHTest *test = [[DIHTest alloc]init];
    HQCDVC.title = @"题库选择";
    HQCDVC.getBlock = ^(Model_Hr_Quesbank_Type *model) {

        self.dataSource = [test getQuesWithBankID:model.BANKID];
        [[TMCache sharedCache]setObject:model.BANKID forKey:@"bankid"];
        [[TMCache sharedCache]setObject:model.BANKNAME forKey:@"bankName"];
        [self initData];

        [self.collectionView reloadData];
        
        [self.button setTitle:model.BANKNAME forState:UIControlStateNormal];
        
    };
    [self presentViewController:navHQCDVC animated:YES completion:NULL];
    
}


- (void)didDeleteButttonClicked:(UIButton *)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要清空该题库所有答题记录吗?"
                                                    message:nil
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    [alert show];
    alert.tag = 300;
    alert.delegate = self;

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 300) {
        switch (buttonIndex) {
            case 0:{
                return;
            }
                break;
            case 1:{
                
                DIHTest *test = [[DIHTest alloc]init];
                NSString *bankid = [[TMCache sharedCache]objectForKey:@"bankid"];
                [test updateDataWithBankid:bankid];
                [self.dataSource removeAllObjects];
                self.dataSource = [test getQuesWithBankID:bankid];
                [self.collectionView reloadData];

            }
                break;
            default:
                break;
        }
    }
}


- (void)initView {
    
    
    
    [self.view addSubview:self.collectionView];
    

}

- (void)initData {

    [self dataSource];
    [self resultArray];
    [self indexPathArray];
    
    
    for (int i = 0; i < _dataSource.count; i++) {
        
        [_resultArray addObject:@[]];
        [_indexPathArray addObject:@[]];
    }
    

}

// 设置单元格的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _dataSource.count;
}

// 设置段数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    
    if (cell) {
        
        for (UIView *view in cell.contentView.subviews) {
            
            if (view) {
                
                [view removeFromSuperview];
            }
        }
    }
    
    
    Model_Hr_Question_Item *model = self.dataSource [indexPath.row];
    
    if ([model.TYPEID isEqualToString:@"1"] || [model.TYPEID isEqualToString:@"3"] || [model.TYPEID isEqualToString:@"4"]) {
    
        DIHTest *test = [[DIHTest alloc]init];
        NSMutableArray *array = [test modelWithTypeId:model.TYPEID];
        Model_Hr_Question_Type *typeModel = array[0];
        NSString *string  = [NSString stringWithFormat:@"(%@)\n%@",typeModel.QUETYPE,model.TITLE];
        CGFloat height = [SizeToFit getHeightByWidth:ScreenWidth - 20 title:string font:[UIFont systemFontOfSize:19]];
        
        
        __weak typeof(self) weakSelf = self;

//        sing.SingleSelectBlock = ^(NSInteger seleIndexPath) {
//            
//
//                
//        };
        
        
        SingleSelectView *singleView = [[SingleSelectView alloc]initWithconfigure:indexPath.row dataArray:self.dataSource headHeight:height + 20 headTitle:string typeid:model.TYPEID];
//        singleView.infoView.SingleSelectBlock = ^(NSIndexPath * seleIndexPath) {
//            NSLog(@"====%@",seleIndexPath);
//            __strong typeof(weakSelf)strongSelf = weakSelf;
//            
//            [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:seleIndexPath inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
//        };

        singleView.frame = cell.contentView.bounds;
        [cell.contentView addSubview:singleView];
        

        singleView.SingleSelectBlock = ^(NSIndexPath *seleIndexPath, NSInteger btnTag ,BOOL isright ,NSInteger state) {
            
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (indexPath.item+1<self.dataSource.count) {
                if (state == 1 ) {
                [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.item + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                }else {
                [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:btnTag inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                }

            }else {
                [HCommon popupErrorMessage:@"已经是最后一题了"];
            }
        };
        
    }else {
    
        NSString *string  = [NSString stringWithFormat:@"%@",model.TITLE];
        CGFloat height = [SizeToFit getHeightByWidth:ScreenWidth - 20 title:string font:[UIFont systemFontOfSize:19]];

        MultiSelectView *multiView = [[MultiSelectView alloc]initWithconfigure:indexPath.row dataArray:self.dataSource headHeight:height + 20 headTitle:string typeid:model.TYPEID];
        multiView.frame = cell.contentView.bounds;
        
        [cell.contentView addSubview:multiView];
        
        __weak typeof(self) weakSelf = self;
        
        multiView.MultiSelectBlock = ^(NSMutableArray * btnTagSum,NSInteger state,NSInteger rows) {
        
            if (indexPath.item+1<self.dataSource.count) {
                if (state == 1) {
                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.item + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                }else {
                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:rows inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                }

            }else {
                
                [HCommon popupErrorMessage:@"已经是最后一题了"];
            }

        };
    }
    return cell;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    [self scrollViewEndScrolling:scrollView.contentOffset];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    [self scrollViewEndScrolling:scrollView.contentOffset];

}

// 设置单元格大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    return CGSizeMake(ScreenWidth, ScreenHeight - 64 );
}

// cell与cell之间的间隔，边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    //上左下右
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

// 设置垂直最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;
}

// 设置水平最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;
}

// 设置标题头大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    return CGSizeMake(0, 0);
}

- (void)scrollViewEndScrolling:(CGPoint)contentOffset {

    NSInteger index = contentOffset.x / ScreenWidth;
    

    
    _currentSelectIndex = index;
}

//上一题下一题
- (void)collectionViewScrollToItem:(BOOL)bl btnTag:(NSInteger)btnTag {
    
   

    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentSelectIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionViewLayout                          = [[UICollectionViewFlowLayout alloc] init]; // 自定义的布局对象
        _collectionView                                = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 , ScreenWidth, ScreenHeight - 64 ) collectionViewLayout:_collectionViewLayout];
        //移动方向
        _collectionViewLayout.scrollDirection          = UICollectionViewScrollDirectionHorizontal;
        //是否显示
        _collectionView.showsHorizontalScrollIndicator = NO;
        //是否有反弹效果
        _collectionView.bounces                        = YES;
        //是否整页翻页
        _collectionView.pagingEnabled                  = YES;
        //数据源代理
        _collectionView.dataSource                     = self;
        _collectionView.delegate                       = self;
        //滚动返回至顶部
        _collectionView.scrollsToTop                   = NO;
        _collectionView.backgroundColor                = [UIColor whiteColor];
        // 注册cell
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    }
    return _collectionView;
}



- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (NSMutableArray *)resultArray {
    if (!_resultArray) {
        _resultArray = [[NSMutableArray alloc]init];
    }
    return _resultArray;
}

- (NSMutableArray *)indexPathArray {
    if (!_indexPathArray) {
        _indexPathArray = [[NSMutableArray alloc]init];
    }
    return _indexPathArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
